

import Vue from 'vue'
import Vuex from 'vuex'
import { COUNTADD , COUNTDESC  } from './type'
import axios from 'axios'
import { obj } from './obj'

Vue.use(Vuex)  // 全局注册声明使用

const store = new Vuex.Store({
    state:{      // 全局的数据状态  所有的组件可以共享数据状态
      count:3000,
      city:"武汉",
      word: "Hello WH2309",
      flag:true,
      data:{
        number:2222,
        list:[],
        test:"test - test - test -测试 "
      },
      msg:"Are YOU oK???",
      comments:[],
      text:"努力学好Vue"
    },
    // 异步数据 action
    actions:{
      // Action 提交的是 mutation，而不是直接变更状态。
      // Action 可以包含任意异步操作。
      changeTest(context,payload){
        context.commit('changeDataTest','22222')  // this.$store.commit("changeDataTest")
      },
      async changeTestAsync({commit} ){
        let res = await axios.get('https://lhx123.love:3333/app/test')
        commit('changeDataTest',res.data.msg)
      },
      async changeListAsync({commit}){
        let res = await axios.post('https://lhx123.love:3333/app/getallinters')
        commit('changeList',res.data.result)
      },
      async changeCommentsAsync({commit}){
        let res = await axios.post('https://lhx123.love:3333/api/comment/list')
        commit('changeComments',res.data.result)
      }
    },
    // 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation 每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)
    mutations:{
      [COUNTADD](state){
        state.count++
      },
      [COUNTDESC](state){
        state.count--
      },
      changeCount(state,payload){
        state.count+=payload
      },
      changeCity(state,payload){
        state.city = payload
      },
      changeWord(state,payload){
        state.word = payload;
      },
      changeFlag(state,payload){
        state.flag = payload
      },
      changeDataNumber(state,payload){
         state.data = {
          ...state.data,
          number:state.data.number + payload
         }
      },
      changeDataTest(state,payload){
        state.data = {
          ...state.data,
          test:payload
        }
      },
      changeMsg(state,payload){
        state.msg = payload;
      },
      changeList(state,payload){
        state.data = {
          ...state.data,
          list:payload
        }
      },
      changeComments(state,payload){
        state.comments = payload;
      },
      changeText(state,payload){
        state.text = payload;
      }
    },
    getters:{
      // 从 store 中的 state 中派生出一些状态，例如对列表进行过滤并计数
      newCount(state){
        return state.count * 10 + 888;
      },
      newword(state){
        return state.word.split('').reverse().join('')
      }
    },
    modules:{
      obj:obj
    }
})

export default store;
